package com.fulihui.information.core.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fulihui.information.core.db.CategoryGroupDB;
import com.fulihui.information.dto.CategoryDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

import static java.util.Collections.emptyList;
import static org.near.toolkit.common.StringUtil.isBlank;
import static org.near.toolkit.common.StringUtil.isNotBlank;
import static org.springframework.util.Assert.hasLength;
import static org.springframework.util.CollectionUtils.isEmpty;

/**
 * 数据结构使用hash，field是父节点，根节点默认使用'ROOT'，值是一个分组下所有类目属性的json array串
 *
 * @author Willard.Hu on 2017/1/16 0016.
 */
@Component("redisCategoryGroupDB")
public class RedisCategoryGroupDB implements CategoryGroupDB {
    /**
     * Redis key的前缀，实际key值是前缀+产品名
     */
    private static final String CATEGORY_CROUP_KEY_PREFIX = "INFORMATION:CATEGORY_CROUP:";
    /**
     * 默认根节点字符串
     */
    private static final String DEFAULT_ROOT_PARENT_CODE  = "ROOT";
    /**
     * 默认key有效时间为5分钟
     */
    private static final int    DEFALUT_EXPIRE_SECONDS    = 300;

    @Autowired
    private JedisPool jedisPool;

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public void save(List<CategoryDTO> list, String parentCode, String productCode) {
        // 集合空，什么都不处理
        if (isEmpty(list)) {
            return;
        }
        // 校验参数
        hasLength(productCode);
        // 执行存储
        String field = isNotBlank(parentCode) ? parentCode : DEFAULT_ROOT_PARENT_CODE;
        try (Jedis jedis = jedisPool.getResource()) {
            String key = CATEGORY_CROUP_KEY_PREFIX + productCode;
            jedis.hset(key, field, JSON.toJSONString(list));
            jedis.expire(key, DEFALUT_EXPIRE_SECONDS);
        }

    }

    @Override
    public List<CategoryDTO> queryGroup(String parentCode, String productCode) {
        // 校验参数
        hasLength(productCode);
        String field = isNotBlank(parentCode) ? parentCode : DEFAULT_ROOT_PARENT_CODE;
        try (Jedis jedis = jedisPool.getResource()) {
            String json = jedis.hget(CATEGORY_CROUP_KEY_PREFIX + productCode, field);
            if (isBlank(json)) {
                return emptyList();
            }
            return JSONArray.parseArray(json, CategoryDTO.class);
        }
    }
}
